<template>
  <view class="cat-group-container">
    <!-- 顶部搜索栏 -->
    <view class="search-bar">
      <view class="search-container">
        <up-search v-model="searchText" placeholder="搜索分组" prefixIcon="search" shape="square" :border="false"
          :clearable="true" :showAction="false" bgColor="#E6E6E7"></up-search>
      </view>

      <view class="add-menu-container">
        <view class="add-button" @tap="handleAddGroup">
          <up-icon name="plus" color="#333" size="20"></up-icon>
        </view>
      </view>
    </view>

    <!-- 导航按钮区域 -->
    <scroll-view scroll-x class="nav-scroll" show-scrollbar="false">
      <view class="nav-bar">
        <view v-for="(item, index) in navItems" :key="index" class="nav-item" :class="{ active: currentNav === item.id }"
          @tap="switchNav(item.id)">
          <text>{{ item.name }}</text>
        </view>
      </view>
    </scroll-view>

    <!-- 分组列表 -->
    <scroll-view scroll-y class="group-list" style="height: calc(100vh - 22vh)">
      <view v-for="(group, index) in groupList" :key="index" class="group-item-wrapper">
        <movable-area class="movable-area">
          <movable-view class="movable-view" direction="horizontal" :out-of-bounds="false" :damping="50" :x="group.x"
            @change="handleMovableChange($event, index)" @touchend="handleTouchend(index)">
            <!-- 分组项主体内容 -->
            <view class="group-item" @tap="handleGroupTap(group)">
              <view class="avatar">
                <image :src="group.avatar" mode="aspectFill"></image>
                <view v-if="group.memberCount" class="member-count">{{ group.memberCount }}</view>
              </view>
              <view class="content">
                <view class="header">
                  <text class="name">{{ group.name }}</text>
                  <text class="time">{{ group.updateTime }}</text>
                </view>
                <view class="description">
                  <text class="text">{{ group.description }}</text>
                </view>
              </view>
            </view>

            <!-- 右侧操作按钮 -->
            <!-- <view class="action-buttons">
              <view class="action-btn edit" @tap="handleEdit(index)">
                <text class="icon">✏️</text>
                <text>编辑</text>
              </view>
              <view class="action-btn delete" @tap="handleDelete(index)">
                <text class="icon">🗑️</text>
                <text>删除</text>
              </view>
            </view> -->
          </movable-view>
        </movable-area>
      </view>
    </scroll-view>
  </view>
</template>

<script setup>
import { ref, reactive, computed } from 'vue';
import { encodeParams } from '@/utils/routerHelper.js';

// 搜索文本
const searchText = ref('');

// 导航项数据
const navItems = [
  { id: 'all', name: '全部' },
  { id: 'recommend', name: '推荐' },
  { id: 'featured', name: '精选' },
  { id: 'recent', name: '最近' },
  { id: 'work', name: '工作' },
  { id: 'study', name: '学习' }
];

// 当前选中的导航项
const currentNav = ref('all');

// 模拟分组列表数据
const allGroupList = reactive([
  {
    id: 1,
    name: '艾尔雷德',
    avatar: '/static/img/chat/testUserA.jpg',
    description: '一位名为艾尔雷德的中世纪炼金术士，掌握古老的神秘学识',
    updateTime: '2024-01-20',
    memberCount: 0,
    x: 0,
    role: 'config',
    category: ['all', 'recent']
  },
  {
    id: 2,
    name: '白雪公主',
    avatar: '/static/img/chat/testUserB.jpg',
    description: '童话故事中的白雪公主，一位美丽纯真的公主，与小动物们为伴，经历过继母的迫害和七个小矮人的帮助',
    updateTime: '2024-01-19',
    memberCount: 0,
    x: 0,
    role: 'snow_white',
    category: ['all', 'featured', 'recommend']
  },
  {
    id: 3,
    name: '德古拉伯爵',
    avatar: '/static/img/chat/testUserA.jpg',
    description: '一位来自特兰西瓦尼亚的古老吸血鬼贵族，拥有数百年的生命经历',
    updateTime: '2024-01-18',
    memberCount: 0,
    x: 0,
    role: 'vampire',
    category: ['all', 'recommend', 'featured']
  }
]);

// 根据当前选中的导航项过滤分组列表
const groupList = computed(() => {
  return allGroupList.filter(group => group.category.includes(currentNav.value));
});

// 切换导航
const switchNav = (navId) => {
  currentNav.value = navId;
};

// 处理滑动变化
const handleMovableChange = (e, index) => {
  const { x } = e.detail;
  // 找到当前操作的项在 allGroupList 中的索引
  const currentGroup = groupList.value[index];
  const allIndex = allGroupList.findIndex(item => item.id === currentGroup.id);
  if (allIndex !== -1) {
    allGroupList[allIndex].x = x;
  }
};

// 处理滑动结束
const handleTouchend = (index) => {
  const currentGroup = groupList.value[index];
  const allIndex = allGroupList.findIndex(item => item.id === currentGroup.id);
  if (allIndex !== -1) {
    const x = allGroupList[allIndex].x;
    if (x < -100) {
      allGroupList[allIndex].x = -280; // 两个按钮的宽度
    } else {
      allGroupList[allIndex].x = 0;
    }
  }
};

// 处理编辑
const handleEdit = (index) => {
  const group = groupList.value[index];
  console.log('编辑分组', group);
  // TODO: 实现编辑功能

  // 重置滑动位置
  const allIndex = allGroupList.findIndex(item => item.id === group.id);
  if (allIndex !== -1) {
    allGroupList[allIndex].x = 0;
  }
};

// 处理删除
const handleDelete = (index) => {
  const group = groupList.value[index];

  uni.showModal({
    title: '确认删除',
    content: '是否确认删除此分组？',
    success: (res) => {
      if (res.confirm) {
        // 从 allGroupList 中删除
        const allIndex = allGroupList.findIndex(item => item.id === group.id);
        if (allIndex !== -1) {
          allGroupList.splice(allIndex, 1);
        }
      } else {
        // 取消删除，重置滑动位置
        const allIndex = allGroupList.findIndex(item => item.id === group.id);
        if (allIndex !== -1) {
          allGroupList[allIndex].x = 0;
        }
      }
    }
  });
};

// 处理添加分组
const handleAddGroup = () => {
  console.log('添加新分组');
  // TODO: 实现添加分组功能
};

// 导入Pinia store
import { useChatMenu } from '@/stores/chatMenu';

// 获取store实例
const chatMenuStore = useChatMenu();

// 处理分组点击
const handleGroupTap = (group) => {
  // 创建新的聊天项
  const newChatItem = {
    id: Date.now(), // 使用时间戳作为临时ID
    name: group.name,
    avatar: group.avatar,
    lastMessage: group.description,
    time: new Date().toLocaleDateString(),
    unread: 0,
    role: group.role,
    isPinned: false,
    isMuted: false,
    x: 0
  };

  // 将新的聊天项添加到store中
  chatMenuStore.chatMenu.unshift(newChatItem);

  // 跳转到聊天详情页面
  // uni.navigateTo({
  //   url: `/pages/chatDetail/chatDetail?id=${newChatItem.id}&name=${encodeURIComponent(group.name)}&avatar=${encodeURIComponent(group.avatar)}&description=${encodeURIComponent(group.description)}&updateTime=${encodeURIComponent(group.updateTime)}&memberCount=${group.memberCount}`
  // });
  uni.navigateTo({
    url: `/pages/chatDetail/chatDetail?data=${encodeParams(newChatItem)}`
  });

};
</script>

<style lang="scss" scoped>
@mixin text-ellipsis {
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
}

.cat-group-container {
  height: 90vh;
  background-color: #fff;
  position: relative;
  display: flex;
  flex-direction: column;

  .search-bar {
    padding: 20rpx 30rpx;
    background-color: #f8f8f8;
    display: flex;
    align-items: center;
    gap: 20rpx;

    .search-container {
      flex: 1;
    }

    .add-menu-container {
      .add-button {
        width: 72rpx;
        height: 72rpx;
        background-color: #e6e6e7;
        border-radius: 16rpx;
        display: flex;
        align-items: center;
        justify-content: center;
        transition: all 0.3s ease;

        &:active {
          background-color: darken(#e6e6e7, 5%);
          transform: scale(0.95);
        }
      }
    }
  }

  .nav-scroll {
    background-color: #fff;
    padding: 10rpx 20rpx;
    border-bottom: 1px solid #f0f0f0;

    .nav-bar {
      display: flex;
      align-items: center;
      justify-content: flex-start;
      width: 100%;
      height: 80rpx;

      .nav-item {
        padding: 0 24rpx;
        margin-right: 16rpx;
        font-size: 28rpx;
        color: #666;
        height: 64rpx;
        line-height: 64rpx;
        border-radius: 32rpx;
        position: relative;
        transition: all 0.25s ease;

        &.active {
          background-color: #ecf5ff;
          color: #2979ff;
          font-weight: 500;
          box-shadow: 0 2rpx 8rpx rgba(41, 121, 255, 0.1);
        }

        &:active {
          opacity: 0.8;
          transform: scale(0.98);
        }
      }
    }
  }

  .group-list {
    .group-item-wrapper {
      width: 100%;

      .movable-area {
        width: 100%;
        height: 140rpx;

        .movable-view {
          width: 100%;
          height: 100%;
          display: flex;

          .group-item {
            width: 100%;
            height: 100%;
            display: flex;
            align-items: center;
            padding: 20rpx 30rpx;
            background-color: #fff;

            .avatar {
              position: relative;
              margin-right: 20rpx;

              image {
                width: 100rpx;
                height: 100rpx;
                border-radius: 50%;
              }

              .member-count {
                position: absolute;
                right: -6rpx;
                top: -6rpx;
                background-color: #2979ff;
                color: #fff;
                font-size: 24rpx;
                padding: 4rpx 12rpx;
                border-radius: 20rpx;
                min-width: 36rpx;
                text-align: center;
              }
            }

            .content {
              flex: 1;

              .header {
                display: flex;
                justify-content: space-between;
                align-items: center;
                margin-bottom: 8rpx;

                .name {
                  font-size: 32rpx;
                  font-weight: 500;
                  color: #333;
                }

                .time {
                  font-size: 24rpx;
                  color: #999;
                }
              }

              .description {
                width: 300rpx;

                .text {
                  font-size: 28rpx;
                  color: #666;
                  @include text-ellipsis;
                  display: inline-block;
                  width: 300rpx;
                }
              }
            }
          }

          .action-buttons {
            display: flex;
            margin-left: auto;

            .action-btn {
              width: 140rpx;
              height: 140rpx;
              display: flex;
              flex-direction: column;
              align-items: center;
              justify-content: center;
              font-size: 24rpx;
              color: #fff;

              .icon {
                font-size: 48rpx;
                margin-bottom: 12rpx;
              }

              &.edit {
                background-color: #ff9800;
              }

              &.delete {
                background-color: #ff5252;
              }

              &:active {
                opacity: 0.8;
              }
            }
          }
        }
      }
    }
  }
}
</style>